package com.ruoyi.business.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

/**
 * @Author: sgchen
 * @Description:
 * @Date: 2025/5/6
 **/
public class WebSocketUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUtil.class);

    /**
     * @Author: sgchen
     * @Description: 使用map进行存储在线的session
     * @Date: 2025/5/6
     **/
    public static final Map<String, Session> ONLINE_SESSION = new ConcurrentHashMap<>();

    /**
     * @Author: sgchen
     * @Description: 添加Session
     * @Date: 2025/5/6
     * @Param userKey:
     * @Param session:
     * @Return:
     **/
    public static void addSession(String userKey, Session session) {
        ONLINE_SESSION.put(userKey, session);
    }

    public static void remoteSession(String userKey) {
        ONLINE_SESSION.remove(userKey);
    }

    public static void remoteAllInValidSession() {
        ONLINE_SESSION.entrySet().removeIf(entry -> !entry.getValue().isOpen());
    }

    /**
     * @Author: sgchen
     * @Description: 向某个用户发送消息
     * @Date: 2025/5/6
     * @Param session:
     * @Param message:
     * @Return:
     **/
    public static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        // getAsyncRemote()和getBasicRemote()异步与同步
        RemoteEndpoint.Basic remote = session.getBasicRemote();
        try {
            remote.sendText(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        RemoteEndpoint.Async async = session.getAsyncRemote();
//        //发送消息
//        Future<Void> future = async.sendText(message);
//        boolean done = future.isDone();
//        LOGGER.info("服务器发送消息给客户端{}的消息:{}，状态为:{}", session.getId(), message, done);

    }

}

